package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.BabyAddRequestBody;
import com.innovation.chengzhangriji.http.BabyPhotoUpdateResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.SelectDateLayout;
import com.innovation.chengzhangriji.ui.widget.SelectRoleLayout;
import com.innovation.chengzhangriji.util.FileUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import java.io.File;

public class BabyInfoFragment extends Fragment implements View.OnClickListener {

    private int mGender;

    private String emptyUrl;

    private RoundedImageView mImageHead;

    private CuteTextView mTextHead;

    private SelectRoleLayout mSelectBaby;

    private SelectRoleLayout mSelectGender;

    private SelectRoleLayout mSelectParent;

    private SelectDateLayout mSelectLmp;

    private SelectDateLayout mSelectDue;

    private SelectDateLayout mSelectBirthday;

    private DisplayImageOptions options;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            String imageUrl = null;
            switch (requestCode) {
                case Config.REQUEST_OPEN_CAMERA:
                    imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                    break;
                case Config.REQUEST_OPEN_PHOTO:
                    imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                    break;
            }
            if (!TextUtils.isEmpty(imageUrl)) {
                File imgFile = new File(imageUrl);
                if (imgFile.exists()) {
                    emptyUrl = imageUrl;
                    ImageLoader.getInstance().displayImage("file://" + imageUrl, mImageHead);
                }
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_baby_info, container, false);
        mImageHead = (RoundedImageView) view.findViewById(R.id.image_head);
        mTextHead = (CuteTextView) view.findViewById(R.id.text_name);
        mSelectBaby = (SelectRoleLayout) view.findViewById(R.id.select_baby);
        mSelectGender = (SelectRoleLayout) view.findViewById(R.id.select_gender);
        mSelectParent = (SelectRoleLayout) view.findViewById(R.id.select_parent);
        mSelectLmp = (SelectDateLayout) view.findViewById(R.id.select_lmp);
        mSelectDue = (SelectDateLayout) view.findViewById(R.id.select_due);
        mSelectBirthday = (SelectDateLayout) view.findViewById(R.id.select_birthday);

        mImageHead.setOnClickListener(this);
        mSelectBaby.setOnClickListener(this);
        mSelectGender.setOnClickListener(this);
        mSelectParent.setOnClickListener(this);
        mSelectLmp.setOnClickListener(this);
        mSelectDue.setOnClickListener(this);
        mSelectBirthday.setOnClickListener(this);

        setOptions();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.select_parent) {
            openParentDialog();
            return;
        }
        // 判断是否为超级管理员
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo == null) {
            return;
        }
        String userId = loginInfo.getUserID();
        int babyId = loginInfo.getBabyID();
        BabyAndParent babyAndParent = DatabaseManager.getInstance(getActivity()).queryBabyAndParent(userId, babyId);
        if (babyAndParent.getRole() != 2) {
            return;
        }
        switch (v.getId()) {
            case R.id.image_head:
                openDialog();
                break;
            case R.id.select_baby:
                openNameDialog();
                break;
            case R.id.select_gender:
                openGenderDialog();
                break;
            case R.id.select_parent:
                openParentDialog();
                break;
            case R.id.select_lmp:
                openDateDialog(Client.STATE_READY, getBaby().getLastDate());
                break;
            case R.id.select_due:
                openDateDialog(Client.STATE_START, getBaby().getDueDate());
                break;
            case R.id.select_birthday:
                openDateDialog(Client.STATE_END, getBaby().getBirthday());
                break;
        }
    }

    public void onClickLeft() {
        // 判断是否有数据为空
        if (TextUtils.isEmpty(mSelectBaby.getText()) || TextUtils.isEmpty(mSelectParent.getText())) {
            ((BabyActivity) getActivity()).tipShow("请填写完整的信息");
            return;
        }
        if (checkChange()) {
            result();
        } else {
            getActivity().finish();
        }
    }

    private Baby getBaby() {
        return ((BabyActivity) getActivity()).getBaby();
    }

    private void init() {
        ImageLoader.getInstance().displayImage(getBaby().getImageUrl(), mImageHead, options);
        mTextHead.setText(getBaby().getName() + "  /  " + getBabyDay(getBaby()));
        mSelectBaby.setText(getBaby().getName());
        mSelectGender.setText(getGender(getBaby().getGender()));
        mSelectParent.setText(getBaby().getParentName());
        mSelectLmp.setText(getDate(getBaby().getLastDate()));
        mSelectDue.setText(getDate(getBaby().getDueDate()));
        mSelectBirthday.setText(getDate(getBaby().getBirthday()));
    }

    private void openNameDialog() {
        final CuteEditText editText = new CuteEditText(getActivity());
        editText.setText(mSelectBaby.getText());
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
        new AlertDialog.Builder(getActivity()).setTitle("修改宝宝名称").setView(editText).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mSelectBaby.setText(editText.getText().toString());
                getBaby().setName(editText.getText().toString());
                mTextHead.setText(getBaby().getName() + "  /  " + getBabyDay(getBaby()));
            }
        }).setNegativeButton("取消", null).show();
    }

    private void openGenderDialog() {
        switch (getBaby().getGender()) {
            case Client.BOY:
                mGender = 0;
                break;
            case Client.GIRL:
                mGender = 1;
                break;
            case Client.UNKNOWN:
                mGender = 2;
                break;
        }
        new AlertDialog.Builder(getActivity()).setTitle("修改宝宝性别")
                .setSingleChoiceItems(new String[]{"男宝", "女宝", "未知"}, mGender, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mGender = which;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (mGender) {
                            case 0:
                                getBaby().setGender(Client.BOY);
                                mSelectGender.setText("男宝");
                                break;
                            case 1:
                                getBaby().setGender(Client.GIRL);
                                mSelectGender.setText("女宝");
                                break;
                            case 2:
                                getBaby().setGender(Client.UNKNOWN);
                                mSelectGender.setText("未知");
                                break;
                        }
                    }
                }).show();
    }

    private void openParentDialog() {
        final CuteEditText editText = new CuteEditText(getActivity());
        editText.setText(mSelectParent.getText());
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        new AlertDialog.Builder(getActivity()).setTitle("修改称谓").setView(editText).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mSelectParent.setText(editText.getText().toString());
                getBaby().setParentName(editText.getText().toString());
            }
        }).setNegativeButton("取消", null).show();
    }

    private void openDateDialog(final int state, long date) {
        if (date == Client.EMPTY_TIME) {
            date = System.currentTimeMillis();
        }
        DateTime dateTime = new DateTime(date);
        final int year = dateTime.getYear();
        final int month = dateTime.getMonthOfYear() - 1;
        final int day = dateTime.getDayOfMonth();
        dateTime.getMillis();
        new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                DateTime dateTime = new DateTime(year, monthOfYear + 1, dayOfMonth, 0, 0);
                long millis = dateTime.getMillis();
                switch (state) {
                    case Client.STATE_READY:
                        getBaby().setLastDate(millis);
                        mSelectLmp.setText(getDate(millis));
                        break;
                    case Client.STATE_START:
                        getBaby().setDueDate(millis);
                        mSelectDue.setText(getDate(millis));
                        break;
                    case Client.STATE_END:
                        getBaby().setBirthday(millis);
                        mSelectBirthday.setText(getDate(millis));
                        break;
                }
                // 判断状态是否变化
                if (getBaby().getState() != Client.STATE_END) {
                    if (getBaby().getDueDate() != Client.EMPTY_TIME) {
                        getBaby().setState(Client.STATE_START);
                    }
                    if (getBaby().getBirthday() != Client.EMPTY_TIME) {
                        getBaby().setState(Client.STATE_END);
                    }
                }
                mTextHead.setText(getBaby().getName() + "  /  " + getBabyDay(getBaby()));
            }
        }, year, month, day).show();
    }

    private void openDialog() {
        final CharSequence[] items = {"拍照", "从手机相册选择"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("添加头像");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (item) {
                    case 0:
                        startHeadCameraForResult();
                        break;
                    case 1:
                        startHeadSelectForResult();
                        break;
                }
            }
        });
        builder.create().show();
    }

    private void startHeadCameraForResult() {
        Intent intent = new Intent(getActivity(), HeadCameraActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_CAMERA);
    }

    private void startHeadSelectForResult() {
        Intent intent = new Intent(getActivity(), HeadPhotoActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_PHOTO);
    }

    private String getGender(int state) {
        String gender = "";
        switch (state) {
            case Client.BOY:
                gender = "男宝";
                break;
            case Client.GIRL:
                gender = "女宝";
                break;
            case Client.UNKNOWN:
                gender = "未知";
                break;
        }
        return gender;
    }

    private String getBabyDayByDueDateOrLastDate(long time) {
        DateTime startTime = new DateTime(time);
        DateTime endTime = new DateTime(System.currentTimeMillis());
        Period pWeek = new Period(startTime, endTime, PeriodType.weeks());
        String week = "";
        String day = "";
        if (pWeek.getWeeks() != 0) {
            week = pWeek.getWeeks() + "周";
        }
        Period pDay = new Period(startTime, endTime, PeriodType.yearWeekDay());
        if (pDay.getDays() != 0) {
            day = pDay.getDays() + "天";
        }
        if (TextUtils.isEmpty(week) && TextUtils.isEmpty(day)) {
            return "孕1天";
        }
        return "孕" + week + day;
    }

    private String getBabyDayByBirthday(long birthday) {
        DateTime startTime = new DateTime(birthday);
        DateTime endTime = new DateTime(System.currentTimeMillis());
        Period p = new Period(startTime, endTime, PeriodType.yearMonthDay());
        String year = "";
        String month = "";
        String day = "";
        if (p.getYears() != 0) {
            year = p.getYears() + "岁";
        }
        if (p.getMonths() != 0) {
            month = p.getMonths() + "月";
        }
        if (p.getDays() != 0) {
            day = p.getDays() + "天";
        }
        if (TextUtils.isEmpty(year) && TextUtils.isEmpty(month) && TextUtils.isEmpty(day)) {
            return "0天";
        }
        return year + month + day;
    }

    private String getBabyDay(Baby baby) {
        switch (baby.getState()) {
            case Client.STATE_READY:
                return "备孕中";
            case Client.STATE_START:
                if (baby.getDueDate() != 0) {
                    return getBabyDayByDueDateOrLastDate(baby.getDueDate() - 280 * 24 * 60 * 60 * 1000l);
                } else {
                    return getBabyDayByDueDateOrLastDate(baby.getLastDate());
                }
            case Client.STATE_END:
                return getBabyDayByBirthday(baby.getBirthday());
        }
        return null;
    }

    private String getDate(long time) {
        if (time == Client.EMPTY_TIME) {
            return null;
        }
        DateTime dateTime = new DateTime(time);
        return "" + dateTime.getYear() + "-" + dateTime.getMonthOfYear() + "-" + dateTime.getDayOfMonth();
    }

    private boolean checkChange() {
        // 判断图片路径是否为空
        if (!TextUtils.isEmpty(emptyUrl)) {
            return true;
        }
        // 判断当前宝贝信息是否和原信息相同
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo != null) {
            String userId = loginInfo.getUserID();
            int babyID = loginInfo.getBabyID();
            Baby baby = DatabaseManager.getInstance(getActivity()).queryBaby(userId, babyID);
            return !(baby.getName().equals(getBaby().getName()) &&
                    baby.getGender().equals(getBaby().getGender()) &&
                    baby.getParentName().equals(getBaby().getParentName()) &&
                    baby.getLastDate().equals(getBaby().getLastDate()) &&
                    baby.getDueDate().equals(getBaby().getDueDate()) &&
                    baby.getBirthday().equals(getBaby().getBirthday()) &&
                    baby.getImageUrl().equals(getBaby().getImageUrl()) &&
                    baby.getState().equals(getBaby().getState()));
        }
        return false;
    }

    private void result() {
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo == null) {
            return;
        }
        if (!TextUtils.isEmpty(emptyUrl)) {
            babyHeadUpload();
        } else {
            babyUpload();
        }
    }

    private void babyHeadUpload() {
        LoginInfo login = Config.getLoginInfo(getActivity());
        if (login == null) {
            return;
        }
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
        String ext = ".jpg";
        String base64 = FileUtils.encodeFileToBase64Binary(new File(emptyUrl));
        Client.requestBabyPhotoUpdate(getActivity(), phone, token, getBaby().getBabyID(), ext, base64, System.currentTimeMillis(), new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                ((BabyActivity) getActivity()).showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Log.d("头像上传成功", "" + value.toString());
                BabyPhotoUpdateResponse response = get(value.toString(), BabyPhotoUpdateResponse.class);
                if (response != null) {
                    if (response.getResult() == 1) {
                        getBaby().setImageUrl(response.getImageUrl());
                        Log.d("网络地址", "" + response.getImageUrl());
                        babyUpload();
                    }
                }
                ((BabyActivity) getActivity()).dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                ((BabyActivity) getActivity()).tipShow(value);
                ((BabyActivity) getActivity()).dismissProgressDialog();
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                ((BabyActivity) getActivity()).tipShow(value);
                ((BabyActivity) getActivity()).dismissProgressDialog();
                getActivity().finish();
            }
        }, ((BabyActivity) getActivity()).networkUnavailableSampleImpl());
    }

    private void babyUpload() {
        final LoginInfo login = Config.getLoginInfo(getActivity());
        if (login == null) {
            return;
        }
        final String phone = login.getPhone();
        final String token = login.getToken().getAccessToken();
        BabyAddRequestBody body = new BabyAddRequestBody();
        body.setName(getBaby().getName());
        body.setGender(getBaby().getGender());
        body.setParentName(getBaby().getParentName());
        body.setLastDate(getBaby().getLastDate());
        body.setDueDate(getBaby().getDueDate());
        body.setBirthday(getBaby().getBirthday());
        body.setImageUrl(getBaby().getImageUrl());
        body.setState(getBaby().getState());
        Client.requestBabyUpdate(getActivity(), phone, token, getBaby().getBabyID(), getBaby().getUpdateTime(), body.getBabyAddRequestBody(), new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                ((BabyActivity) getActivity()).showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                getBaby().setNoteName(getBaby().getName() +"的成长日记");
                ((BabyActivity) getActivity()).updateBaby(getBaby());
                ((BabyActivity) getActivity()).updateTimeline(getBaby().getBabyID(), getBaby().getParentName());
                ((BabyActivity) getActivity()).dismissProgressDialog();
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
            }

            @Override
            public void onChZhRJFailure(String value) {
                ((BabyActivity) getActivity()).dismissProgressDialog();
                ((BabyActivity) getActivity()).tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                ((BabyActivity) getActivity()).dismissProgressDialog();
                ((BabyActivity) getActivity()).tipShow(value);
                getActivity().finish();
            }
        }, ((BabyActivity) getActivity()).networkUnavailableSampleImpl());
    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_head_unknown)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_head_unknown)  //image连接地址为空时
                .showImageOnFail(R.drawable.ic_head_unknown)  //image加载失败
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }
}
